package database.team.phase2;

import java.io.BufferedReader;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class SortedJoin {
	public void sortJoin() throws IOException{
	String absPathTables,valuePK,valueFK,tupleContent,tupleMatch = null;
	int empIDPK,EmpIDFKDept,numOfTuplesEmp = 0, numOfTuplesDept=0;
	File file = new File("Tables");
	
	//Read the tables in order to join in a new file called SortedJoin.txt
	absPathTables = file.getAbsolutePath();
	File folder = new File(absPathTables);
	File[] table = folder.listFiles();
	BufferedReader tableEmpSize = new BufferedReader(new FileReader(table[0]));
	while(tableEmpSize.readLine() != null)
    {		
            numOfTuplesEmp++;
    }
	BufferedReader tableDeptSize = new BufferedReader(new FileReader(table[1]));
     while(tableDeptSize.readLine() != null)
     {
             numOfTuplesDept++;
     }
    
  	BufferedReader tableEmp = new BufferedReader(new FileReader(table[0]));
 	
 	
	
	FileWriter output = new FileWriter("SortedJoin.txt");
	PrintWriter tuple = new PrintWriter(output);
	for(int i=0; i < numOfTuplesEmp; i++){
	    valuePK = tableEmp.readLine();
		empIDPK = Integer.parseInt(valuePK.substring(0, 7));
		BufferedReader tableDept = new BufferedReader(new FileReader(table[1]));
		for(int j=0; j < numOfTuplesDept; j++){
			valueFK = tableDept.readLine();
			EmpIDFKDept = Integer.parseInt(valueFK.substring(0, 7));
			if(empIDPK == EmpIDFKDept){
				tupleMatch = valueFK;
			}
		}
		tupleContent = tupleMatch;
		tuple.println(tupleContent);
		tableDept.close();
	}
	
	 //Closing the tempFile, tuple and output readers and writers
	  tableEmp.close(); tuple.close(); output.close();
		  //RunPhase1.phase2_counterIO++;
	}
	 public static void main(String[] args) {
		 System.out.println("Joining the table employee with Department");
		 long startTime = System.currentTimeMillis();
		 SortedJoin joinTables = new SortedJoin();
		 try {
			joinTables.sortJoin();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		 long endTime = System.currentTimeMillis();
		 float totalTime = (endTime - startTime);
		 
         System.out.println("Total time to Join the tables: "+totalTime); 
		 System.out.println("The result is shown in the file SortedJoin.txt");
	 }
}
